package com.tao.mydownloadlibrary.helper;

import com.tao.mydownloadlibrary.info.DownloadInfo;
import com.tao.mydownloadlibrary.info.TaskInfo;
import com.tao.mydownloadlibrary.utils.Lg;
import com.tao.mydownloadlibrary.utils.MD5Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.List;

/**
 * reate by tao on{DATE}
 */
public class FileMager {

    public static void mergeFiles(DownloadInfo downloadInfo, List<TaskInfo> taskInfos) throws Exception {
        File file = new File(downloadInfo.getPath() + File.separator + downloadInfo.getFileName());
        if (!file.exists()) {
            file.getParentFile().mkdirs();
            if (file.isDirectory())
                file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                throw new Exception("file create error");
            }
        } else {
            file.delete();
        }

        for (TaskInfo taskInfo : taskInfos) {
            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
            accessFile.setLength(downloadInfo.getProgress());
            Lg.e(taskInfo);
            long offeset = taskInfo.getOffeset();
            long threadLen = taskInfo.getThreadLen();
            accessFile.seek(offeset);
            File cacheFile = new File(taskInfo.getCacheFile());
            FileInputStream inputStream = new FileInputStream(cacheFile);

            byte[] buff = new byte[1024 * 1024 * 3];
            int len = 0;
            while ((len = inputStream.read(buff, 0, buff.length)) != -1) {
                accessFile.write(buff, 0, len);
            }
            cacheFile.delete();
            try {
                inputStream.close();
                accessFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (taskInfos.size() > 0) {
            try {
                new File(taskInfos.get(0).getCacheFile()).getParentFile().delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        downloadInfo.setMd5(MD5Util.getMD5fromBigFile(file));

    }

}
